import { AfterViewInit, Component, ElementRef, OnInit, ViewChild } from '@angular/core'

@Component({
  selector: 'app-ex0601',
  templateUrl: './ex0601.component.html',
  styleUrls: ['./ex0601.component.scss']
})
export class Ex0601Component implements OnInit, AfterViewInit {
  protected cnv: any
  protected ctx: any

  @ViewChild('canvas')
  set canvas(ref: ElementRef) {
    this.cnv = ref.nativeElement
    this.ctx = ref.nativeElement.getContext('2d')
  }

  constructor() {
  }

  ngOnInit(): void {
  }

  ngAfterViewInit(): void {
    // this.draw1(this.ctx)
    // this.draw2(this.ctx)
    // this.draw3(this.ctx)
    // this.draw4(this.ctx)
    this.draw5(this.ctx)
  }

  draw1(ctx): void {
    const image = new Image()
    image.src = 'assets/images/pic.jpg'
    image.onload = () => {
      ctx.drawImage(image, 40, 20)
    }
  }

  draw2(ctx): void {
    const image = new Image()
    image.src = 'assets/images/pic.jpg'
    image.onload = () => {
      ctx.drawImage(image, 40, 20, 200, 200)
    }
  }

  draw3(ctx): void {
    const image = new Image()
    image.src = 'assets/images/pic.jpg'
    image.onload = () => {
      ctx.drawImage(image, 280, 120, 220, 220, 40, 20, 200, 200)
    }
  }

  draw4(ctx): void {
    const image = new Image()
    image.src = 'assets/images/flower.jpg'
    image.onload = () => {
      ctx.fillStyle = ctx.createPattern(image, 'repeat')
      // ctx.fillStyle = ctx.createPattern(image, 'repeat-x')
      // ctx.fillStyle = ctx.createPattern(image, 'repeat-y')
      ctx.fillRect(0, 0, this.cnv.width, this.cnv.height)
    }
  }

  draw5(ctx): void {
    const bgCanvas = document.createElement('canvas')
    bgCanvas.width = 20
    bgCanvas.height = 20
    const bgCtx = bgCanvas.getContext('2d')
    bgCtx.beginPath()
    bgCtx.arc(10, 10, 10, 0, 2 * Math.PI, true)
    bgCtx.closePath()
    bgCtx.fillStyle = 'HotPink'
    bgCtx.fill()

    ctx.fillStyle = ctx.createPattern(bgCanvas, 'repeat-x')
    ctx.fillRect(0, 0, 200, 200)
  }
}
